package com.example.springcloudwinter.service;


import com.example.springcloudwinter.bo.BusinessBo;
import com.example.springcloudwinter.bo.CartBo;
import com.example.springcloudwinter.bo.FoodBo;
import com.example.springcloudwinter.feign.BusinessFeignClient;
import com.example.springcloudwinter.dto.ResultEntity;
import com.example.springcloudwinter.mapper.CartMapper;
import com.example.springcloudwinter.dto.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private BusinessFeignClient businessFeignClient;

    public ResultEntity<?> listCart(String userId, int businessId){
        ResultEntity<Map<?,Object>> result=new ResultEntity<>();
        List<FoodBo> list;
        BusinessBo businessBo;
        Map<String, Object>map=new HashMap<>();
        try {
            list=cartMapper.getFoodById(businessId,userId);
            businessBo = businessFeignClient.getBusinessById(businessId).getDetail();
            map.put("foods",list);
            map.put("business", businessBo);
            result.setDetail(map).setCode(200);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public ResultEntity<?> saveCart(String userId,int businessId, int foodId){
        ResultEntity<?> result=new ResultEntity<>();
        CartBo cartEntity;
        try {
            cartEntity=cartMapper.listSpecificCart(businessId,userId,foodId);
            if(cartEntity!=null){
                cartMapper.updateCart(userId,businessId,foodId,cartEntity.getQuantity()+1);
                result.setCode(200);
            }
            else if(cartMapper.saveCart(userId, businessId, foodId)<=0)return result;
            else result.setCode(200);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public ResultEntity<?> removeCart(String userId,int businessId,int foodId){
        ResultEntity<?> result=new ResultEntity<>();
        CartBo cartEntity;
        try {
            cartEntity=cartMapper.listSpecificCart(businessId,userId,foodId);
            if(cartEntity!=null){
                if(cartEntity.getQuantity()-1>0) {
                    cartMapper.updateCart(userId, businessId, foodId, cartEntity.getQuantity() - 1);
                    result.setCode(200);
                }
                else{
                    if (cartMapper.removeCart(userId, businessId, foodId)<=0)return result;
                    else result.setCode(200);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}
